import { fabric } from 'fabric';
import { IEditor } from '@/types/global';

class ZoomPlugin {
  canvas: fabric.Canvas;
  editor: IEditor;
  centerPoint: { x: number; y: number };
  static pluginName = 'ZoomPlugin';
  static apis: string[] = ['setZoom', 'setCenterPoint'];

  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
    this.centerPoint = { x: 0, y: 0 };
  }
  // 设置中心原点
  setCenterPoint(x: number, y: number) {
    this.centerPoint.x = x;
    this.centerPoint.y = y;
  }

  // 设置缩放级别
  setZoom(val: number, type: string) {
    const { canvas } = this;
    let zoom: number;
    if (type === 'click') {
      zoom = canvas.getZoom();
      zoom = Number((Math.floor((zoom + val) * 100) / 100).toFixed(2));
      if (zoom > 4) zoom = 4; // 限制最大缩放级别
      if (zoom < 0.1) zoom = 0.1; // 限制最小缩放级别
    } else {
      zoom = val;
    }
    canvas.zoomToPoint(this.centerPoint, zoom);
  }
}
export default ZoomPlugin;
